import { getToken } from "@/utils/auth";
import { close, increase, start } from "@/utils/nporgress";
import { ElMessage } from "element-plus";
import type { Router } from "vue-router";
import { createRouter, createWebHistory } from "vue-router";

const router: Router = createRouter({
  history: createWebHistory(import.meta.env.VITE_APP_ENV),
  routes: [
    {
      path: "/chat",
      component: () => import("@/views/chat.vue")
    },
    {
      path: "/",
      redirect: "/hello"
    },
    {
      path: "/icon",
      name: "icon",
      component: () => import("@/components/icons/IconLogo.vue")
    },
    {
      path: "/hello",
      name: "hello",
      component: () => import("@/views/HelloView.vue")
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/LoginView.vue")
    },

    {
      path: "/register",
      name: "register",
      component: () => import("@/views/RegisterView.vue")
    },
    {
      path: "/home",
      name: "home",
      redirect: "index",
      component: () => import("@/views/HomeView.vue"),
      children: [
        {
          name: "displayList",
          path: "/index",
          component: () => import("@/components/Q&A/QuestionDisplayList.vue")
        },
        {
          path: "/heat",
          component: () => import("@/components/Q&A/QuestionDisplayHeat.vue")
        },
        {
          path: "/id",
          name: "Question",
          component: () => import("@/components/Q&A/QuestionItem.vue")
        },
        {
          path: "/addQuestion",
          name: "AddQuestion",
          component: () => import("@/components/Q&A/QuestionAdd.vue")
        },
        {
          path: "/personalSpace",
          name: "PersonalSpace",
          component: () => import("@/components/PersonalSpace/PersonalSpace.vue")
        }
      ]
    }

  ]
});

router.beforeEach(async (to, from) => {
  start();
  // 如果用户已登录
  // 优化以下代码
  if (getToken()) {
    if (to.name === "hello" || to.name === "login" || to.name === "register") {
      increase();
      ElMessage({
        message: "欢迎回来！！",
        type: "success"
      });
      return { name: "home" };
    } else {
      increase();
      return;
    }
  } else {
    if (to.name === "hello" || to.name === "login" || to.name === "register") {
      increase();
      return;
    } else {
      increase();
      return { name: "hello" };
    }
  }

});

router.afterEach(async (to, from) => {
  close();
});

export default router;
